//https://leetcode-cn.com/problems/add-two-numbers/submissions/


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

//解题思路
// 链表从头到尾是个位到高位
// 从低位开始相加 使用inBit存储进位
// 使用链表的尾插创建一个链表,一个一个插入构成结果
struct ListNode* buyNode(int x)
{
    struct ListNode* ret = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(ret);
    ret->val = x;
    ret->next = NULL;
    return ret;
}
//尾插
void tailPush(struct ListNode** pphead, int x)
{
    assert(pphead);

    if(NULL == *pphead)
    {
        *pphead = buyNode(x);
        return;
    }

    struct ListNode* tail = *pphead;

    while(tail->next != NULL)
    {
        tail = tail->next;
    }

    tail->next = buyNode(x);
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
    //创建一个链表
    struct ListNode* L = NULL;

    struct ListNode* list1 = l1;
    struct ListNode* list2 = l2;
    
    //进位
    int inBit = 0;

    while(list1 || list2)
    {
        if(list1 != NULL && list2 != NULL)
        {
            tailPush(&L, (list1->val + list2->val + inBit) % 10);
            
            inBit = (list1->val + list2->val + inBit) / 10;

            list1 = list1->next;
            list2 = list2->next;

        }
        else if(list1 == NULL && list2 != NULL)
        {
            tailPush(&L, (list2->val + inBit) % 10);
            inBit = (list2->val + inBit) / 10;

            list2 = list2->next;
        }
        else if(list1 != NULL && list2 == NULL)
        {
            tailPush(&L, (list1->val + inBit) % 10);
            inBit = (list1->val + inBit) / 10;

            list1 = list1->next;

        }

    }
    if(inBit == 1)
    {
        tailPush(&L, inBit);
    }
    return L;
}